﻿using Microsoft.Extensions.Options;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Demo.Net.RabbitMQ
{
    public class RabbitMQFactory: IRabbitMQFactory
    {

        private readonly IOptionsMonitor<RabbitMQClientOptions> _optionsMonitor;

        public RabbitMQFactory(IOptionsMonitor<RabbitMQClientOptions> optionsMonitor)
        {
            _optionsMonitor = optionsMonitor ?? throw new ArgumentNullException(nameof(optionsMonitor));
        }

        public IRabbitMQClient Get(string ?name = null)
        {
            name = name ?? "Default";
            var options = _optionsMonitor.Get(name);
            var factory = new ConnectionFactory
            {
                HostName = options.HostName,
                Port = options.Port,
                UserName = options.UserName,
                Password = options.Password
            };

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            if (options.RabbitMQClient == null)
            {
                lock (name)
                {
                    options.RabbitMQClient = new RabbitMQClient(options,factory);
                }
            }

          return new RabbitMQClient(options, factory);
        }
    }
}
